package br.com.lazyprogrammer.social.infestit.social.facebook;

import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.AccessTokenSource;
import com.facebook.FacebookException;
import com.facebook.FacebookRequestError;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.Builder;
import com.facebook.widget.WebDialog.OnCompleteListener;

import java.util.ArrayList;
import java.util.List;

public class FacebookDAO implements OnCompleteListener {

	private Context context;

	private StatusCallback statusCallback;

    private String fbId, permissions;

	public FacebookDAO() {
		super();
	}

	public FacebookDAO(Context context, StatusCallback statusCallback, String fbId, String permissions) {
		super();
		this.context = context;
		this.statusCallback = statusCallback;
        this.fbId = fbId;
        this.permissions = permissions;
	}

	public static void login(Context context, StatusCallback statusCallback, String fbId, String permissions) {
		Bundle parameters = new Bundle();
		parameters.putString("response_type", "code");
		parameters.putString("scope", permissions);
		Builder webDialog = new Builder(context, fbId, "oauth", parameters);
		WebDialog dialog = webDialog.build();
		dialog.setOnCompleteListener(new FacebookDAO(context, statusCallback, fbId, permissions));
		dialog.show();
	}

	public static void handleRequestError(Context context,
			FacebookRequestError error) {
		String message = "";
		switch (error.getErrorCode()) {
		case 506:
			message = "Por favor utilizar par�metros diferentes. N�o � permitido spam.";
			break;

		default:
			message = error.getErrorMessage();
			break;
		}
		Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
		toast.show();
	}

	@Override
	public void onComplete(Bundle values, FacebookException error) {
		if (values != null) {

			List<String> permissoes = new ArrayList<String>();
			for (String permissao : permissions.split(",")) {
				permissoes.add(permissao);
			}
			Session.openActiveSessionWithAccessToken(context, AccessToken
					.createFromExistingAccessToken(
							values.getString("access_token"), null, null,
							AccessTokenSource.WEB_VIEW, permissoes),
					statusCallback);
		}
	}

}
